package com.sgq.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sgq.dto.RolePermissionDTO;
import com.sgq.entity.Role;
import com.sgq.service.PermissionService;
import com.sgq.service.RoleService;
import com.sgq.utils.Result;
import com.sgq.vo.RolePermissionVo;
import com.sgq.vo.RoleQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sgq
 * @since 2024-09-13
 */
@RestController
@RequestMapping("/api/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/{id}")
    public Result getRoleById(@PathVariable("id") Long id){
        return Result.ok(roleService.getById(id));
    }

    @GetMapping("/list")
    public Result list(){
        List<Role> list = roleService.list();
        return Result.ok(list);
    }

    @GetMapping("/page")
    public Result page(RoleQueryVo roleQueryVo){
        IPage<Role> page = roleService.findPage(roleQueryVo);
        return Result.ok(page);
    }

    @PostMapping("/save")
    public Result save(@RequestBody Role role){
        return Result.ok(roleService.save(role));
    }

    @PutMapping("/update")
    public Result update(@RequestBody Role role){
        return Result.ok(roleService.updateById(role));
    }

    /**
     *  根据role_id删除角色 & 角色与权限的关系
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result update(@PathVariable("id") Long id){

        if(roleService.removeRoleAndRelationship(id)){

            return Result.ok().message("角色删除成功");
        }
        return Result.error().message("角色删除失败");
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestBody Long [] ids){
        return Result.ok(roleService.removeBatchByIds(Arrays.asList(ids)));
    }

    /**
     * 分配权限时先获取之前权限分配情况
     * @param userId
     * @param roleId
     * @return
     */
    @GetMapping("/getAssignPermissionTree")
    public Result getAssignPermissionTree(Long userId, Long roleId) {
        //调用查询权限树数据的方法
        RolePermissionVo permissionTree = permissionService.findPermissionTree(userId, roleId);
        //返回数据
        return Result.ok(permissionTree);
    }

    /**
     * 分配权限-保存权限数据
     *
     * @param rolePermissionDTO
     * @return
     */
    @PostMapping("/saveRoleAssign")
    public Result saveRoleAssign(@RequestBody RolePermissionDTO rolePermissionDTO) {
        if (roleService.saveRolePermission(rolePermissionDTO.getRoleId(), rolePermissionDTO.getList())) {
            return Result.ok().message("权限分配成功");
        } else {
            return Result.error().message("权限分配失败");
        }
    }

}

